<template>
	<view class="container">

		<!-- 认证状态提示 -->
		<view class="status-tip" v-if="isCertified">
			<view class="tip-content">
				<image src="/static/my/组 9(3).png" class="tip-icon"></image>
				<text class="tip-text">您已完成身份认证</text>
			</view>
		</view>

		<!-- 认证表单 -->
		<view class="form-container">
			<view class="form-section">
				<text class="section-title">基本信息</text>
				
				<view class="form-item" @click="startEdit('name')">
					<text class="label">姓名 <text class="required">*</text></text>
					<input 
						class="input" 
						v-model="formData.name" 
						placeholder="请输入真实姓名"
						:disabled="!isEditing"
						@click.stop
					/>
				</view>

				<view class="form-item" @click="startEdit('sex')">
					<text class="label">性别 <text class="required">*</text></text>
					<view class="radio-group" @click.stop>
						<view 
							class="radio-item" 
							:class="{ active: formData.sex === '男' }"
							@click="selectSex('男')"
						>
							<text class="radio-text">男</text>
						</view>
						<view 
							class="radio-item" 
							:class="{ active: formData.sex === '女' }"
							@click="selectSex('女')"
						>
							<text class="radio-text">女</text>
						</view>
					</view>
				</view>

				<view class="form-item" @click="startEdit('nation')">
					<text class="label">民族 <text class="required">*</text></text>
					<input 
						class="input" 
						v-model="formData.nation" 
						placeholder="请输入民族"
						:disabled="!isEditing"
						@click.stop
					/>
				</view>

				<view class="form-item" @click="startEdit('birthday')">
					<text class="label">出生日期 <text class="required">*</text></text>
					<picker 
						mode="date" 
						:value="formData.birthday" 
						@change="onBirthdayChange"
						:disabled="!isEditing"
						@click.stop
					>
						<view class="picker-input">
							<text class="picker-text" :class="{ placeholder: !formData.birthday }">
								{{ formData.birthday || '请选择出生日期' }}
							</text>
							<image src="/static/my/收起箭头小 拷贝.png" class="picker-arrow"></image>
						</view>
					</picker>
				</view>

				<view class="form-item" @click="startEdit('idCard')">
					<text class="label">身份证号 <text class="required">*</text></text>
					<input 
						class="input" 
						v-model="formData.idCard" 
						placeholder="请输入身份证号码"
						:disabled="!isEditing"
						@click.stop
					/>
				</view>

				<view class="form-item" @click="startEdit('address')">
					<text class="label">地址 <text class="required">*</text></text>
					<input 
						class="input" 
						v-model="formData.address" 
						placeholder="请输入详细地址"
						:disabled="!isEditing"
						@click.stop
					/>
				</view>
			</view>

			<view class="form-section">
				<text class="section-title">身份证照片</text>
				
				<view class="photo-upload">
					<view class="photo-item">
						<text class="photo-label">身份证正面</text>
						<view class="photo-uploader" @click="uploadPhoto('front')">
							<image 
								v-if="formData.front" 
								:src="formData.front" 
								class="photo-preview"
								mode="aspectFill"
							/>
							<view v-else class="photo-placeholder">
								<image src="/static/my/组 9(4).png" class="upload-icon"></image>
								<text class="upload-text">点击上传</text>
							</view>
						</view>
					</view>

					<view class="photo-item">
						<text class="photo-label">身份证反面</text>
						<view class="photo-uploader" @click="uploadPhoto('opposite')">
							<image 
								v-if="formData.opposite" 
								:src="formData.opposite" 
								class="photo-preview"
								mode="aspectFill"
							/>
							<view v-else class="photo-placeholder">
								<image src="/static/my/组 9(4).png" class="upload-icon"></image>
								<text class="upload-text">点击上传</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button 
				v-if="!isEditing && isCertified"
				class="edit-btn" 
				@click="startEditing"
			>
				修改信息
			</button>
			<view v-if="isEditing" class="edit-buttons">
				<button 
					class="cancel-btn" 
					@click="cancelEdit"
				>
					取消
				</button>
				<button 
					class="save-btn" 
					@click="saveIdentity"
					:disabled="isLoading"
				>
					{{ isLoading ? '保存中...' : '保存修改' }}
				</button>
			</view>
			<button 
				v-if="!isCertified"
				class="save-btn" 
				@click="saveIdentity"
				:disabled="isLoading"
			>
				{{ isLoading ? '保存中...' : '保存认证信息' }}
			</button>
		</view>
	</view>
</template>

<script>
	import IdentityAPI from '@/api/identity.js'
	import authManager from '@/utils/auth.js'

	export default {
		data() {
			return {
				// 表单数据
				formData: {
					uid: null,
					name: '',
					sex: '',
					nation: '',
					birthday: '',
					address: '',
					idCard: '',
					front: '',
					opposite: ''
				},
				// 状态
				isLoading: false,
				isCertified: false,
				isEditing: false, // 是否处于编辑状态
				// 用户ID
				userId: null
			}
		},
		onLoad() {
			// 获取用户ID
			this.userId = authManager.getUserInfo()?.userId
			if (!this.userId) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
				return
			}
			
			this.formData.uid = this.userId
			this.loadIdentityInfo()
		},
		methods: {
			// 开始编辑
			startEditing() {
				this.isEditing = true
				console.log('开始编辑模式')
			},
			
			// 取消编辑
			cancelEdit() {
				this.isEditing = false
				// 重新加载原始数据
				this.loadIdentityInfo()
				console.log('取消编辑，恢复原始数据')
			},
			
			// 点击字段开始编辑
			startEdit(field) {
				if (this.isCertified && !this.isEditing) {
					this.startEditing()
				}
			},

			// 选择性别
			selectSex(sex) {
				if (this.isEditing || !this.isCertified) {
					this.formData.sex = sex
				}
			},

			// 选择出生日期
			onBirthdayChange(e) {
				if (this.isEditing || !this.isCertified) {
					this.formData.birthday = e.detail.value
				}
			},

			// 上传照片
			uploadPhoto(type) {
				if (this.isCertified && !this.isEditing) return
				
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						// 这里应该上传到服务器，暂时使用本地路径
						this.formData[type] = tempFilePath
						uni.showToast({
							title: '照片选择成功',
							icon: 'success'
						})
					},
					fail: (err) => {
						console.error('选择照片失败:', err)
						uni.showToast({
							title: '选择照片失败',
							icon: 'none'
						})
					}
				})
			},

			// 加载身份认证信息
			async loadIdentityInfo() {
				try {
					const response = await IdentityAPI.getIdentityInfo(this.userId)
					console.log('身份认证信息:', response)
					
					if (response.data) {
						// 根据API返回的数据结构，检查identity对象
						const identityData = response.data.identity || response.data
						const hasIdentity = response.data.hasIdentity
						
						console.log('认证状态检查:', {
							hasIdentity: hasIdentity,
							identityData: identityData,
							name: identityData?.name
						})
						
						// 检查是否有有效的认证信息（至少要有姓名）
						const hasValidData = identityData && identityData.name && identityData.name.trim() !== ''
						
						if (hasValidData) {
							this.formData = { ...this.formData, ...identityData }
							this.isCertified = true
							console.log('用户已完成身份认证，数据:', identityData)
						} else {
							console.log('用户未完成身份认证，数据为空或无效')
							this.isCertified = false
						}
					} else {
						console.log('用户未完成身份认证，无数据')
						this.isCertified = false
					}
				} catch (error) {
					console.error('加载身份认证信息失败:', error)
					// 如果是404，说明还没有认证信息，这是正常的
					if (error.code !== 404) {
						uni.showToast({
							title: '加载信息失败',
							icon: 'none'
						})
					}
					this.isCertified = false
				}
			},

			// 保存身份认证信息
			async saveIdentity() {
				// 表单验证
				if (!this.validateForm()) {
					return
				}

				this.isLoading = true

				try {
					const response = await IdentityAPI.saveIdentity(this.formData)
					console.log('保存身份认证信息成功:', response)
					
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})

					// 如果是编辑模式，退出编辑状态
					if (this.isEditing) {
						this.isEditing = false
						this.isCertified = true
						// 重新加载数据以更新显示
						this.loadIdentityInfo()
					} else {
						// 如果是首次认证，返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}

				} catch (error) {
					console.error('保存身份认证信息失败:', error)
					uni.showToast({
						title: error.message || '保存失败',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},

			// 表单验证
			validateForm() {
				const { name, sex, nation, birthday, address, idCard } = this.formData
				
				if (!name.trim()) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					})
					return false
				}

				if (!sex) {
					uni.showToast({
						title: '请选择性别',
						icon: 'none'
					})
					return false
				}

				if (!nation.trim()) {
					uni.showToast({
						title: '请输入民族',
						icon: 'none'
					})
					return false
				}

				if (!birthday) {
					uni.showToast({
						title: '请选择出生日期',
						icon: 'none'
					})
					return false
				}

				if (!idCard.trim()) {
					uni.showToast({
						title: '请输入身份证号',
						icon: 'none'
					})
					return false
				}

				// 身份证号格式验证
				const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
				if (!idCardRegex.test(idCard)) {
					uni.showToast({
						title: '身份证号格式不正确',
						icon: 'none'
					})
					return false
				}

				if (!address.trim()) {
					uni.showToast({
						title: '请输入地址',
						icon: 'none'
					})
					return false
				}

				return true
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}


	/* 认证状态提示 */
	.status-tip {
		background-color: #e8f5e8;
		margin: 40rpx 20rpx 20rpx;
		border-radius: 20rpx;
		padding: 30rpx;
	}

	.tip-content {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.tip-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.tip-text {
		color: #52c41a;
		font-size: 28rpx;
		font-weight: 500;
	}

	/* 表单容器 */
	.form-container {
		padding: 20rpx;
	}

	.form-section {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
		cursor: pointer;
		transition: background-color 0.2s;
		padding: 8rpx;
		border-radius: 12rpx;
	}

	.form-item:hover {
		background-color: #f8f9fa;
	}

	.label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		font-weight: 500;
	}

	.required {
		color: #ff4d4f;
	}

	.input {
		width: 100%;
		height: 80rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333;
		border: 2rpx solid transparent;
		box-sizing: border-box;
	}

	.input:focus {
		border-color: #3183FB;
		background-color: white;
	}

	.input:disabled {
		background-color: #f0f0f0;
		color: #999;
	}

	/* 性别选择 */
	.radio-group {
		display: flex;
		gap: 20rpx;
	}

	.radio-item {
		flex: 1;
		height: 80rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 2rpx solid transparent;
		transition: all 0.3s;
	}

	.radio-item.active {
		background-color: #e6f7ff;
		border-color: #3183FB;
	}

	.radio-text {
		font-size: 28rpx;
		color: #333;
	}

	.radio-item.active .radio-text {
		color: #3183FB;
		font-weight: 500;
	}

	/* 日期选择器 */
	.picker-input {
		height: 80rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border: 2rpx solid transparent;
	}

	.picker-input:active {
		border-color: #3183FB;
		background-color: white;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
	}

	.picker-text.placeholder {
		color: #999;
	}

	.picker-arrow {
		width: 24rpx;
		height: 24rpx;
	}

	/* 照片上传 */
	.photo-upload {
		display: flex;
		gap: 20rpx;
	}

	.photo-item {
		flex: 1;
	}

	.photo-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		font-weight: 500;
	}

	.photo-uploader {
		height: 200rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
		border: 2rpx dashed #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.photo-preview {
		width: 100%;
		height: 100%;
	}

	.photo-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10rpx;
	}

	.upload-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
	}

	/* 操作按钮 */
	.action-buttons {
		padding: 40rpx 20rpx;
	}

	.save-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #3183FB 0%, #3183FB 100%);
		border: none;
		border-radius: 44rpx;
		color: white;
		font-size: 32rpx;
		font-weight: 500;
	}

	.save-btn:disabled {
		background: #ccc;
	}

	.edit-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #FF9800 0%, #FF9800 100%);
		border: none;
		border-radius: 44rpx;
		color: white;
		font-size: 32rpx;
		font-weight: 500;
	}

	.edit-buttons {
		display: flex;
		gap: 20rpx;
	}

	.cancel-btn {
		flex: 1;
		height: 88rpx;
		background: #f5f5f5;
		border: 2rpx solid #ddd;
		border-radius: 44rpx;
		color: #666;
		font-size: 32rpx;
		font-weight: 500;
	}

	.edit-buttons .save-btn {
		flex: 2;
	}
</style>